<template>
  <q-page class="q-pa-md wrapBox" v-loading="loading">
    <div class="nav">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <el-image
            src="/svgs/modelApplication.svg"
            style="width: 17px; margin-top: 2px"
            fit
          />
        </el-breadcrumb-item>
        <el-breadcrumb-item>模型服务</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ name: 'model-app' }">模型应用</el-breadcrumb-item>
        <el-breadcrumb-item><span style="color: #333;">模型详情</span></el-breadcrumb-item>
      </el-breadcrumb>
    </div>
<!--    <div style="position: relative; ">-->
<!--      <q-breadcrumbs class="q-mb-md" style="height:50px;line-height: 40px; border-bottom: 1px dashed #ccc;">-->
<!--        <div style="width: 100%;display: flex;justify-content: space-between">-->
<!--          <div>-->
<!--            <el-icon style="cursor: pointer;" @click="router.go(-1)">-->
<!--              <ArrowLeft />-->
<!--            </el-icon>-->
<!--            <q-breadcrumbs-el label="显示模型名称" />-->
<!--          </div>-->
<!--          <div>-->
<!--&lt;!&ndash;            <el-button  type="primary" plain :disabled="modelVesrionCompare" @click="modelVersionCompare">模型版本对比</el-button>&ndash;&gt;-->
<!--            <el-button  type="primary" plain @click="addModelVersion">新增模型版本</el-button>-->
<!--          </div>-->
<!--        </div>-->
<!--      </q-breadcrumbs>-->
<!--    </div>-->
    <div class="datasetBox" style="position: relative">
      <div class="title">模型信息</div>
      <div class="contentBox">
        <div class="dataBox">
          <div class="row">
            <div class="col">模型ID：<i>{{ modelDetailInfo.id }}</i></div>
            <div class="col">模型名称：<i>{{ modelDetailInfo.title }}</i></div>
            <div class="col">创建人：<i>{{ modelDetailInfo.creator_username }}</i></div>
          </div>
          <div class="row">
            <div class="col">模型说明：<i>{{ modelDetailInfo.description }}</i></div>
            <div class="col">创建时间：<i>{{ modelDetailInfo.create_at }}</i></div>
            <div class="col"></div>
          </div>
        </div>
      </div>
      <div style="width: 100%;height: 20px;background-color: #F6F8FA"></div>
<!--      <div style="line-height: 60px; border-bottom: 1px dashed #ccc;margin: 20px 0;color: #333;">-->
<!--        模型版本 <el-button  type="primary" style="margin-left: 10px" :plain="modelCompareData" @click="modelVersionCompare">比对</el-button>-->
<!--      </div>-->
      <div class="subTitle">
        模型版本 <el-button  type="primary" style="float:right;margin-bottom: 10px" :disabled="modelCompareData" :plain="modelCompareData" @click="modelVersionCompare">比对</el-button>
      </div>
      <div class="contentBox">
        <div class="dataBox">
          <el-table
            :data="labelAssignData"
            style="width: 100%;font-size: 12px;"
            :header-cell-style="{ background: '#eee', color: '#333333',textAlign: 'left' }"
            :cell-style="{textAlign: 'left' }"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column align="center" prop="version_number" label="版本号" width="200">
              <template #default="scope">
                <el-button link type="primary" size="small" @click="toAssessmentReport(scope.row)">{{ scope.row.version_number }}</el-button>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="dockerStatus" label="状态"  width="200" />
            <el-table-column align="center" prop="create_at" label="创建时间"  width="200" />
            <el-table-column align="center" prop="description" label="版本说明"  width="200" />
            <el-table-column align="center" prop="labels" label="操作">
              <!--        v-if="scope.row.dockerStatus === '构建失败'"-->
              <template #default="scope">
                <el-button v-if="scope.row.dockerStatus === '构建成功'" link type="primary" size="small" @click="toModelDeploy">部署</el-button>
                <el-button v-if="scope.row.dockerStatus === '构建成功'" link type="primary" size="small" @click="toAssessmentReport(scope.row)">评估报告</el-button>
                <el-button link type="primary" size="small" @click="deleteVersion(scope.row)">删除</el-button>
                <el-button v-if="scope.row.dockerStatus === '构建失败'" link type="primary" size="small" @click="dailyRecord(scope.row)">日志</el-button>
                <el-button v-if="scope.row.dockerStatus === '构建失败'" link type="primary" size="small" @click="reconfiguration(scope.row)">模型镜像重新构建</el-button>
                <el-button v-if="scope.row.dockerStatus === '构建成功'" link type="primary" size="small" @click="mirrorAddressDialog(scope.row)">镜像地址</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <el-dialog v-model="deleteModelVersionDialog" :show-close="false" width="500px" :close-on-click-modal="false">
      <template #header="{}">
        <div style="display: flex;justify-content:space-between;margin-top: 10px">
          <div style="display:flex;">
            <el-icon style="font-size: 20px; color: #FFA940"><WarningFilled /></el-icon>
            <span style="margin-left: 10px;color: #FFA940;font-weight: bold">删除提醒</span>
          </div>
        </div>
      </template>
      <div style="margin: 0 0 0 50px">
        <p style="letter-spacing:2px;">确定删除本模型的{{ modelVersionInfo.version_number }}版本吗?</p>
        <p style="letter-spacing:2px;">删除后不可恢复,请谨慎操作!</p>
      </div>
      <div style="display: flex;justify-content: flex-end; padding: 0;margin-right: 60px;padding: 10px 0">
        <el-button type="primary" @click="deleteModelVersionDialog = false">放弃删除</el-button>
        <el-button @click="emitDeleteModelVersion">继续删除</el-button>
      </div>
    </el-dialog>
    <!--镜像弹框-->
    <el-dialog v-model="mirrorAddressDialogShow" :show-close="false" width="500px" :close-on-click-modal="false">
      <template #header="{}">
        <div style="display: flex;justify-content:space-between;margin-top: 10px">
          <div style="display:flex;">
            <span style="margin-left: 10px;color: #1D1D1D;font-weight: bold">镜像地址</span>
          </div>
        </div>
      </template>
      <div style="display: flex; padding-left: 60px;align-items: center;margin-top: 20px">
        镜像地址: <el-input disabled="false" style="width: 80%;margin-left: 10px" v-model="mirrorAddressValue" spellcheck="false"></el-input>
      </div>
      <div style="display: flex;width: 100%;padding: 0;margin-top: 40px;border-top: 1px solid rgb(234,234,234);padding: 5px 0">
        <div style="flex: 1;text-align: center;line-height: 30px;cursor: pointer;border-right: 1px solid rgb(234, 234, 234)" @click="mirrorAddressDialogShow = false">返回</div>
        <div style="flex: 1;text-align: center;line-height: 30px;color: rgb(58,141,255);cursor: pointer" @click="copyButton">复制</div>
      </div>
    </el-dialog>
    <!--失败日志-->
    <el-dialog v-model="dailyRecordDialogShow" width="500px" :close-on-click-modal="false">
      <template #header="{}">
        <div style="display: flex;justify-content:space-between;margin-top: 10px">
          <div style="display:flex;justify-content: center;width: 100%">
            <span style="margin-left: 10px;color: #1D1D1D;font-weight: bold;text-align: center">日志信息</span>
          </div>
        </div>
      </template>
      <div v-if="boxLoadState && !showNoDataTextState" style="position:relative;height:200px;">
        <box-loading></box-loading>
      </div>
      <div>
        <div style="max-height: 400px;overflow: auto">
          <div class="logBox" v-html="logData"></div>
        </div>
        <div style="display: flex;width: 100%;padding: 0;border-top: 1px solid rgb(234,234,234)">
          <div style="flex: 1;text-align: center;line-height: 30px;color: rgb(58,141,255);cursor: pointer" @click="downloadButton(logData,'log')">下载</div>
        </div>
      </div>
    </el-dialog>
  </q-page>
</template>


<script setup lang="ts">

import { ref,toRaw, nextTick } from "vue";
import { useRouter } from 'vue-router';
import { getModelAppDetail, getModelVersionsList, deleteModelVersion,errorLog,modelReconfiguration } from 'src/api/model'
import { modelStore } from 'src/stores/model';
import useClipboard from 'vue-clipboard3';
const router = useRouter()
const showModelStore = modelStore()
const userStatus = JSON.parse(localStorage.getItem('user') || "{}").status;//判断用户是否是项目创建人或项目管理员
const userInfoName = localStorage.getItem('username')//获取用户登录的用户名
const projectId = router.currentRoute.value.params.project_id
const repository_model_id = showModelStore.repository_model_id
const loading = ref(false)
import {ElMessage, ElMessageBox} from 'element-plus';
import {downloadFeatureset} from "src/api/dataset";
const modelDetailInfo = ref({});
let modelCompareData = ref(true);//多个模型版本修改显示
let selectModelVersionData:any = [];
let mirrorAddressDialogShow = ref(false);
let dailyRecordDialogShow = ref(false);//失败日志
let mirrorAddressValue = ref('');
const logData = ref('');
let dialogId = ref(0);//日志id
const boxLoadState = ref(false)
const showNoDataTextState = ref(false)
//点击新增模型版本
const addModelVersion = () => {
  router.push({ name: 'model-add-version', params: { project_id: projectId } })
}

// 导入历史数据
const labelAssignData = ref([])

//获取创建的模型详情信息
getModelDetail()
function getModelDetail() {
  loading.value = true
  getModelAppDetail(projectId,repository_model_id).then( (res:any) => {
    loading.value = false
    modelDetailInfo.value = res.data;
  }).catch(error => {
    loading.value = false
    ElMessage.error(`请求详情数据报错,提示${error.data}`)
  })
}

//获取仓库模型版本列表
getModelVersions();
function getModelVersions() {
  loading.value = true
  getModelVersionsList(projectId,repository_model_id).then( (res:any) => {
    loading.value = false;
    res.data.forEach( (item:any) => {
      item.dockerStatus = dockerStatusChange(item.docker_image_status);
    })
    labelAssignData.value = res.data
  }).catch( (error:any) => {
    loading.value = false
    ElMessage.error(`请求详情数据报错,提示${error.data}`)
  })
}
function dockerStatusChange(dockerStatus:string){
  switch (dockerStatus) {
    case 'building':
      return '构建中';
    case 'available':
      return '构建成功';
    case 'fail':
      return '构建失败';
    case 'initial':
      return '初始化';
  }
}
//多个模型版本对比
function handleSelectionChange (value:any) {
  if( value.length > 1 ){
    modelCompareData.value = false
  }else {
    modelCompareData.value = true
  }
  selectModelVersionData = toRaw(value);
}
//点击跳转模型对比界面
const modelVersionCompare = () => {
  if( modelCompareData.value ){
    return ;
  }
  let modelVersionData = JSON.parse(JSON.stringify(selectModelVersionData));
  let versions = modelVersionData.map( (items:any) =>{
      return items.id
  })
  showModelStore.setCompareVersions(versions);
  router.push({ name:'model-app-compare' })
}

//点击跳转模型部署
const toModelDeploy = () =>{
  router.push({ name:'model-deploy-create' })
}
//点击跳转评估报告
const toAssessmentReport = (row:any) =>{
  showModelStore.setVersionId(toRaw(row.id))
  router.push({ name:'assessment-report' })
}
//删除模型版本
const deleteModelVersionDialog = ref(false)
const modelVersionInfo = ref({})
function deleteVersion (row:any) {
  modelVersionInfo.value = toRaw(row)
  deleteModelVersionDialog.value = true
}
function emitDeleteModelVersion () {
  const version_id = modelVersionInfo.value.id;
  deleteModelVersion(projectId,repository_model_id,version_id).then( (res:any) => {
    ElMessage.success(`成功删除模型版本！！！`)
    deleteModelVersionDialog.value = false;
    getModelVersions();
  })
}

//失败日志
function dailyRecord (row:any) {
  loading.value = true
  logData.value = '';
  dialogId.value = row.id;
  errorLog(projectId,repository_model_id,row.id).then( res =>{
    modelStore().setErrorData(res.data);
    let routeData = router.resolve({ name: 'errorData' })
    if (routeData) {
      nextTick(() => {
        window.open(routeData.href, '_blank')
      })
    }
    loading.value = false
  })
}
//模型镜像重构
function reconfiguration(row:any){
  modelReconfiguration(projectId,repository_model_id,row.id).then( res =>{
    getModelVersions();
  })
}
//镜像地址弹框
function mirrorAddressDialog (row:any) {
  mirrorAddressValue.value = row.docker_image_address
  mirrorAddressDialogShow.value = true;
}
// 复制镜像地址
const { toClipboard } = useClipboard()
const copyButton = async () => {
  try {
    await toClipboard(mirrorAddressValue.value)
    ElMessage({
      message: '数据集链接已复制',
      type: 'success',
    })
  } catch (e) {
    console.error(e)
  }
}
//下载
function downloadButton(data: any, name: string){
  ElMessageBox.confirm('确定下载该日志数据吗？', '日志下载', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'success'
  }).then(() => {
    let urlObject = window.URL || window.webkitURL || window;
    let export_blob = new Blob([data]);
    let save_link = document.createElement("a")
    save_link.href = urlObject.createObjectURL(export_blob);
    save_link.download = name;
    save_link.click();
  })
}
</script>

<style lang="scss" scoped>

.wrapBox {
  padding: 0 !important;
  .nav {
    display: flex;
    align-items: center;
    padding-left: 20px;
    cursor: pointer;
    background-color: #f6f8fa;
    height: 46px;
    ::v-deep .el-breadcrumb {
      display: flex;
      align-items: center;
    }
  }
  .datasetBox {
    margin: 0 20px;
    .title {
      width: 100%;
      padding: 12px;
      box-sizing: border-box;
      background-color: #fff;
      color: #333;
      font-size: 16px;
      font-weight: 500;
      text-align: left;
      line-height: 24px;
      border-bottom: 2px solid #f6f8fa;
    }
    .subTitle{
      display: flex;
      justify-content: space-between;
      align-items: center;
      color: #333;
      font-size: 16px;
      background-color: #fff;
      padding: 12px 12px 0 12px;
      border-bottom: 2px solid #f6f8fa;
    }
    .contentBox {
      padding: 12px;
      background-color: #ffffff !important;
      .demo-tabs {
        margin-top: 40px;
      }
    }
  }
}
//面包屑斜杆
::v-deep .el-breadcrumb__separator {
  font-size: 14px !important;
  color: #c9cdd4 !important;
  margin-top: 2px !important;
}
//面包屑字体颜色
::v-deep .el-breadcrumb__inner {
  color: #666 !important;
}
::v-deep .el-tabs__active-bar {
  display: none;
}
::v-deep .el-breadcrumb__inner.is-link,
.el-breadcrumb__inner a {
  font-weight: normal !important;
}
::v-deep .el-dialog__body{
  padding-top: 15px;
  padding-bottom: 0;
}
.dataBox {
  padding: 10px 0 0 20px;
  .row {
    margin-bottom: 10px;

    i {
      font-style: initial;
      color: #333333;
    }
  }
}

.dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  display: inline-block;
  margin: 0 10px 0 -10px;
}

.successDot {
  background: #1FB62F;
}

.errorDot {
  background: #E6376E;
}
</style>
